package com.amigo.online.message.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.amigo.online.message.entity.MIMCTokerResponse;
//import com.amigo.online.message.entity.AuthMessage;
import com.amigo.online.message.enums.Imconfig;
import com.amigo.online.message.enums.MIMCUrlEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;
@Slf4j
public class MIMCHttpUtil {

    public static HttpHeaders getUserHttpHeaders(String userId){
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Content-Type","application/json");
//        requestHeaders.add("appKey", MIMCEnum.MESSAGE.getAppKey());
//        requestHeaders.add("appSecret", MIMCEnum.MESSAGE.getAppSecret());
//        requestHeaders.add("ownerAccount", userId);
        requestHeaders.add("token", getTokenString(userId));

        return requestHeaders;
    }

    /**
     * 获取带ImToken的请求头
     * @param token
     * @return
     */
    public static HttpHeaders getTokenHeaders(String token){
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/json");
        headers.add("Accept", "application/json;charset=UTF-8");
        headers.add("token", token);
        return headers;
    }
    /**
     * 鉴权
     */
    public static MIMCTokerResponse getToken(String userId){
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(new AuthMessage(userId)));
        RestTemplate restTemplate =new RestTemplate();
        MIMCTokerResponse mimcTokerResponse = restTemplate.postForEntity(MIMCUrlEnum.TOKEN.getValue(), jsonObject, MIMCTokerResponse.class).getBody();
        if(!mimcTokerResponse.getMessage().equals("success")){
            log.error("token获取失败:   " + mimcTokerResponse.getMessage());
        }
        log.info("getToken返回值：" + JSONObject.toJSONString(mimcTokerResponse.getData()));
        return mimcTokerResponse;
    }
    public static String getTokenString(String userId){
        MIMCTokerResponse mimcTokerResponse = getToken(userId);
        return mimcTokerResponse.getData().getToken();
    }
    public static void main(String[] args) {
        System.out.println(MIMCHttpUtil.getToken("1"));
    }
}


/**
 * 鉴权时发送的消息
 */
@Data
class AuthMessage {

    private  String  appKey = Imconfig.appKey;
    private  String appSecret = Imconfig.appSecret;
    private  String appId = Imconfig.appId ;
    private String regionKey = Imconfig.regionKey;
    private String appAccount;

    public AuthMessage(String appAccount) {
        this.appAccount = appAccount;
    }
}
